/**
 * 获取当前页面路径
 */
const getCurrentPage = () => {
  let curPages = getCurrentPages();
  let curPage = curPages[curPages.length - 1];
  if (curPage) {
    let url = '/' + curPage.route;
    let options = curPage.options;
    let params = [];
    for (const key in options) {
      if (options.hasOwnProperty(key)) {
        params.push(key + '=' + options[key]);
      }
    }
    if (params.length > 0) {
      url += '?' + params.join('&');
    }
    return url
  }
}


/*函数节流*/
function throttle(fn, interval) {
  var enterTime = 0; //触发的时间
  var gapTime = interval || 300; //间隔时间，如果interval不传值，默认为300ms
  return function() {
    var that = this;
    var backTime = new Date(); //第一次函数return即触发的时间
    if (backTime - enterTime > gapTime) {
      fn.call(that, arguments);
      enterTime = backTime; //赋值给第一次触发的时间 保存第二次触发时间
    }
  };
}
function throttle1(fn, time) {
    let timer = null
    time = time || 1000
    return function (...args) {
      if (timer) {
        return
      }
      const _this = this
      timer = setTimeout(() => {
        timer = null
      }, time)
      fn.apply(_this, args)
    }
}
function debounce1(fn, time) {
    let timer = undefined
    return function() {
      if (timer !== undefined) {
        window.clearTimeout(timer)
      }
      timer = setTimeout(() => {
        fn.call()
        timer = undefined
      }, time)
    }
} 
function debounce1(func, delay = 0) {
  let timer = null;
  return function (...arg) {
	clearTimeout(timer);
	timer = setTimeout(() => {
	  func.apply(this, arg)
	}, delay)
  }
}
/*函数防抖*/
function debounce(fn, interval) {
  var timer;
  var gapTime = interval || 1000; //间隔时间 不传值默认为1000ms
  console.log(interval)
  return function() {
    clearTimeout(timer);
    var that = this;
    var args = arguments; //保存arguments setTimeout是全局的 arguments不是防抖函数需要的
    timer = setTimeout(function() {
      fn.call(that, args);
    }, gapTime);
  };
}

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatTime2 = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return [year, month, day].map(formatNumber).join('-');
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const isEmpty = s => {
  return undefined == s || '' == s || null == s || 'null' == s;
}

function base64Encode(str) { // 编码，配合encodeURIComponent使用
  var c1, c2, c3;
  var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var i = 0,
    len = str.length,
    strin = '';
  while (i < len) {
    c1 = str.charCodeAt(i++) & 0xff;
    if (i == len) {
      strin += base64EncodeChars.charAt(c1 >> 2);
      strin += base64EncodeChars.charAt((c1 & 0x3) << 4);
      strin += "==";
      break;
    }
    c2 = str.charCodeAt(i++);
    if (i == len) {
      strin += base64EncodeChars.charAt(c1 >> 2);
      strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
      strin += base64EncodeChars.charAt((c2 & 0xF) << 2);
      strin += "=";
      break;
    }
    c3 = str.charCodeAt(i++);
    strin += base64EncodeChars.charAt(c1 >> 2);
    strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
    strin += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
    strin += base64EncodeChars.charAt(c3 & 0x3F)
  }
  return strin
}

function base64Decode(input) { // 解码，配合decodeURIComponent使用
  var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var output = "";
  var chr1, chr2, chr3;
  var enc1, enc2, enc3, enc4;
  var i = 0;
  input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  while (i < input.length) {
    enc1 = base64EncodeChars.indexOf(input.charAt(i++));
    enc2 = base64EncodeChars.indexOf(input.charAt(i++));
    enc3 = base64EncodeChars.indexOf(input.charAt(i++));
    enc4 = base64EncodeChars.indexOf(input.charAt(i++));
    chr1 = (enc1 << 2) | (enc2 >> 4);
    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
    chr3 = ((enc3 & 3) << 6) | enc4;
    output = output + String.fromCharCode(chr1);
    if (enc3 != 64) {
      output = output + String.fromCharCode(chr2);
    }
    if (enc4 != 64) {
      output = output + String.fromCharCode(chr3);
    }
  }
  // console.log(output);
  return utf8Decode(output);
}


function utf8Decode(utftext) { // utf-8解码
  var string = '';
  let i = 0;
  let c = 0;
  let c1 = 0;
  let c2 = 0;
  while (i < utftext.length) {
    c = utftext.charCodeAt(i);
    if (c < 128) {
      string += String.fromCharCode(c);
      i++;
    } else if ((c > 191) && (c < 224)) {
      c1 = utftext.charCodeAt(i + 1);
      string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
      i += 2;
    } else {
      c1 = utftext.charCodeAt(i + 1);
      c2 = utftext.charCodeAt(i + 2);
      string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
      i += 3;
    }
  }
  return string;
}

function verifyPhone(phone) {
  // let reg = /^[\d]{11}$/;
  let reg = /^1[3|4|5|7|8][0-9]{9}$/
  return phone == undefined || phone == '' || reg.test(phone);
}


function message(msg, success) {
  uni.showModal({
    title: '温馨提示',
    content: msg,
    showCancel: false,
    confirmColor: "#59A5F0",
    success: success
  })
}

function confirm(msg, success, fail) {
  uni.showModal({
    title: '温馨提示',
    content: msg,
    showCancel: true,
    confirmColor: "#59A5F0",
    cancelColor: "#59A5F0",
    success: success,
    fail: fail
  })
}

function loadingShow() {
  uni.showToast({
    title: '加载中',
    icon: 'loading',
    duration: 120000
  })
}

function tips(msg) {
  uni.showToast({
    title: msg,
    icon: 'none',
    duration: 1500
  })
}

function formatCity(cityName) {
  // '广州市'----->'广州'
  if (isEmpty(cityName)) {
    return;
  }
  var L = cityName.length - 1;
  cityName = cityName.substring(0, L);
  return cityName;
}

const wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1]; // 加权因子
const valideCode = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2]; // 身份证验证位值.10代表X
/**
 * 验证身份证
 * @param idCard 需要验证的身份证号
 * @returns 匹配返回true 不匹配返回false
 */
function idCardValidate(idCardValue) {
  //去掉字符串头尾空格
  idCardValue = valueTrim(idCardValue.replace(/ /g, ""));
  if (idCardValue.length == 18) {
    // 得到身份证数组
    let a_idCard = idCardValue.split("");
    //进行18位身份证的基本验证和第18位的验证
    if (isValidityBrithBy18IdCard(idCardValue) && isTrueValidateCodeBy18IdCard(a_idCard)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
};

/**
 * 判断身份证号码为18位时最后的验证位是否正确
 * @param a_idCard 身份证号码数组
 * @return
 */
function isTrueValidateCodeBy18IdCard(a_idCard) {
  let sum = 0; // 声明加权求和变量
  if (a_idCard[17].toLowerCase() == 'x') {
    a_idCard[17] = 10; // 将最后位为x的验证码替换为10方便后续操作
  }

  for (let i = 0; i < 17; i++) {
    sum += wi[i] * a_idCard[i]; // 加权求和
  }
  let valCodePosition = sum % 11; // 得到验证码所位置
  if (a_idCard[17] == valideCode[valCodePosition]) {
    return true;
  } else {
    return false;
  }
};
/**
 * 验证18位数身份证号码中的生日是否是有效生日
 * @param idCard 18位书身份证字符串
 * @return
 */
function isValidityBrithBy18IdCard(idCard18) {
  let year = idCard18.substring(6, 10);
  let month = idCard18.substring(10, 12);
  let day = idCard18.substring(12, 14);
  let temp_date = new Date(year, parseFloat(month) - 1, parseFloat(day));
  // 这里用getFullYear()获取年份，避免千年虫问题
  if (temp_date.getFullYear() != parseFloat(year) ||
    temp_date.getMonth() != parseFloat(month) - 1 ||
    temp_date.getDate() != parseFloat(day)) {
    return false;
  } else {
    return true;
  }
};
//去掉字符串头尾空格
function valueTrim(str) {
  return str.replace(/(^\s*)|(\s*$)/g, "");
}

function checkBankCard(bankno) {
  let lastNum = bankno.substr(bankno.length - 1, 1); //取出最后一位（与luhn进行比较）

  let first15Num = bankno.substr(0, bankno.length - 1); //前15或18位
  let newArr = new Array();
  for (let i = first15Num.length - 1; i > -1; i--) { //前15或18位倒序存进数组
    newArr.push(first15Num.substr(i, 1));
  }
  let arrJiShu = new Array(); //奇数位*2的积 <9
  let arrJiShu2 = new Array(); //奇数位*2的积 >9

  let arrOuShu = new Array(); //偶数位数组
  for (let j = 0; j < newArr.length; j++) {
    if ((j + 1) % 2 == 1) { //奇数位
      if (parseInt(newArr[j]) * 2 < 9)
        arrJiShu.push(parseInt(newArr[j]) * 2);
      else
        arrJiShu2.push(parseInt(newArr[j]) * 2);
    } else //偶数位
      arrOuShu.push(newArr[j]);
  }

  let jishu_child1 = new Array(); //奇数位*2 >9 的分割之后的数组个位数
  let jishu_child2 = new Array(); //奇数位*2 >9 的分割之后的数组十位数
  for (let h = 0; h < arrJiShu2.length; h++) {
    jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
    jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
  }

  let sumJiShu = 0; //奇数位*2 < 9 的数组之和
  let sumOuShu = 0; //偶数位数组之和
  let sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和
  let sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和
  let sumTotal = 0;
  for (let m = 0; m < arrJiShu.length; m++) {
    sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
  }

  for (let n = 0; n < arrOuShu.length; n++) {
    sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
  }

  for (let p = 0; p < jishu_child1.length; p++) {
    sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
    sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
  }
  //计算总和
  sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);

  //计算luhn值
  let k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
  let luhn = 10 - k;

  if (lastNum == luhn) {
    return true;
  } else {
    return false;
  }
}

function isMoney(str) {
  var reg = /^(([1-9][0-9]{0,7})|([0]\.\d{1,2})|([1-9][0-9]{0,7}\.\d{1,2}))$/;
  if (reg.test(str)) {
    return true;
  } else {
    return false;
  }
}

function switchTabLoc(url) {
  uni.switchTab({
    url: url,
    fail: err => {
      uni.navigateTo({
        url: url
      });
    }
  })
}

function verifyEmail(email) {
  let reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
  return email == undefined || email == '' || reg.test(email);
}

function formateMoney(money) {
  money = money.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
  money = money.replace(/^\./g, ""); //验证第一个字符是数字而不是
  money = money.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
  money = money.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
  money = money.replace(/^(\-)*(\d+)\.(\d{2}).*$/, '$1$2.$3'); //只能输入2个小数
  return money
}

function totalMoney(price, num) {
  if (!isEmpty(price) && !isEmpty(num)) return price * num
  else return 0
}

function showLoading(msg) {
  uni.showLoading({
    title: msg,
    mask: true,
    duration: 1500
  })
}

function hideLoading() {
  uni.hideLoading()
}

const formatCouponDate = list => {
  for (let i = 0; i < list.length; i++) {
    if (list[i].hasOwnProperty('expireBeginTime') && list[i].hasOwnProperty('expireEndTime')) {
      list[i].expireBeginTime = formatDotDate(list[i].expireBeginTime)
      list[i].expireEndTime = formatDotDate(list[i].expireEndTime)
    } else if (list[i].hasOwnProperty('beginTime') && list[i].hasOwnProperty('endTime')) {
      list[i].beginTime = formatDotDate(list[i].beginTime)
      list[i].endTime = formatDotDate(list[i].endTime)
    }
  }
  return list
}

function add0(m) {
  return m < 10 ? '0' + m : m
}

function isMobile(str) {
  if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(str))) {
    return false;
  }
  return true;
}

const formatDotDate = shijianchuo => {
  var date = new Date(shijianchuo.replace(/-/g, '/'));
  const year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  const t1 = year + '.' + add0(month) + '.' + add0(day)
  return `${t1}`
}

function dateStrToTimestamp(dateStr) {
  if (isEmpty(dateStr)) {
    return
  }
  //dataStr: 2021-08-31 17:59:00.0
  dateStr = dateStr.substring(0, 19);
  dateStr = dateStr.replace(/-/g, '/'); //必须把日期'-'转为'/'
  var timestamp = new Date(dateStr).getTime();
  return timestamp
}

//获取当前页面路径及参数
function getCurrentPageUrlWithArgs() {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const url = currentPage.route
  const options = currentPage.options
  let urlWithArgs = `/${url}?`
  for (let key in options) {
    const value = options[key]
    urlWithArgs += `${key}=${value}&`
  }
  urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
  return urlWithArgs
}

function getDistance(lat1, lng1, lat2, lng2) {
  // lat1用户的纬度
  // lng1用户的经度
  // lat2商家的纬度
  // lng2商家的经度
  var radLat1 = Rad(lat1);
  var radLat2 = Rad(lat2);
  var a = radLat1 - radLat2;
  var b = Rad(lng1) - Rad(lng2);
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math
    .sin(b / 2), 2)));
  s = s * 6378.137;
  s = Math.round(s * 10000) / 10000;
  s = s.toFixed(2); //保留两位小数
  return s
}

function Rad(d) { //根据经纬度判断距离
  return d * Math.PI / 180.0;
}

function openLocation(addrInfo, userLat, userLng) {
  var that = this;
  var address = addrInfo.address,
    name = addrInfo.name,
    latitude = addrInfo.lat,
    longitude = addrInfo.lng;
  if (isEmpty(latitude) || isEmpty(latitude)) {
    return
  }
	// #ifdef MP-UNIONPAY
	upsdk.pluginReady(function() {
		upsdk.navi({
			sLat: userLat, // 起点纬度
			sLon: userLng, // 起点经度
			sName: '我的位置', // 起点名称
			dLat: addrInfo.lat, // 终点维度
			dLon: addrInfo.lng, // 终点经度
			dName: addrInfo.name, // 终点名称
			success: function() {
				console.log("调用地理位置导航成功")
				// 成功回调 
			},
			fail: function(msg) {
				console.log("调用地理位置导航失败", msg)
				// 失败回调
			}
		});
	});
	// #endif
	// #ifndef MP-UNIONPAY
	uni.openLocation({
		latitude: parseFloat(latitude),
		longitude: parseFloat(longitude),
		name: name,
		address: address
	});
	// #endif
}

/**
 * URL解码，当链接中含有编译后的&符号时将其去除
 * @param {*} url 
 */
function decodeUrl(url) {
  let link = decodeURIComponent(url)
  if (link.indexOf('&amp;') > -1) {
    link = link.replaceAll('&amp;', '&')
  }
  return link
}

function attachedUrl(relativePath, baseUrl) {
  if (undefined == relativePath || '' == relativePath || null == relativePath) {
    return '';
  } else {
    if (-1 != relativePath.indexOf('attached') && -1 == relativePath.indexOf('http')) {
      return baseUrl + '/' + relativePath;
    } else {
      return relativePath;
    }
  }
}
/**
 * 跳转至轮播图配置的页面
 * page: banner返回的对象
 * pageDictionary: 页面字典对象
 * isJump: 是否跳转（0：跳转，1：不跳转）
 * pageType: 要跳转的页面类型（0：小程序页面，1：URL链接）
 * path: 要跳转的小程序页面路径
 * url：要跳转的H5页面路径
 * pageSource: 页面来源（0：内部页面，1：外部页面）
 * appId:要跳转的外部小程序APPID（当pageSource为1时有效）
 * jumpMode：跳转类型（0：普通跳转，1：重定向，2：tab跳转）
 */
function toBannerUrl(page) {
  if (!page) return
  if ('1' == page.isJump || !page.pageDictionary) return
  let pageDictionary = page.pageDictionary
  if ('1' == pageDictionary.pageType) {
    //H5页面跳转到含有webview组件的页面
    let url = pageDictionary.url;
	let title = pageDictionary.title
    if (url) {
      let navUrl = encodeURIComponent(url);
	  let MiniOpenId = uni.getStorageSync('MiniOpenId');
	  if(!MiniOpenId) {
		  uni.switchTab({
		  	url: '/pages/my/my'
		  });
		  uni.setStorageSync('outlink',navUrl)
	  } else {
		 uni.navigateTo({
			url: '/pages/outlink/outlink?outlink=' + navUrl,
		 })
	  }
    }
  } else if ('0' == pageDictionary.pageType) {
    if ('1' == pageDictionary.pageSource) {
      if (pageDictionary.appId) {
        uni.navigateToMiniProgram({
          appId: pageDictionary.appId,
          path: pageDictionary.path
        })
      }
    } else if ('0' == pageDictionary.pageSource) {
      if ('0' == pageDictionary.jumpMode) {
        uni.navigateTo({
          url: pageDictionary.path
        })
      } else if ('1' == pageDictionary.jumpMode) {
        uni.redirectTo({
          url: pageDictionary.path
        })
      } else if ('2' == pageDictionary.jumpMode) {
        uni.switchTab({
          url: pageDictionary.path,
					fail() {
						uni.navigateTo({
						  url: pageDictionary.path,
						})
					}
        })
      }
    }
  } else if ('2' == pageDictionary.pageType) {
		// #ifdef H5 || MP-UNIONPAY
		//H5页面跳转到含有webview组件的页面
		let url = pageDictionary.url;
		if (url) {
		  let navUrl = encodeURIComponent(url);
		  console.log(navUrl);
		  uni.navigateTo({
		    url: '/pages/outlink/outlink?outlink=' + navUrl,
		  })
		}
		// #endif
		// #ifdef MP-WEIXIN
		if ('1' == pageDictionary.pageSource) {
		  if (pageDictionary.appid) {
		    uni.navigateToMiniProgram({
		      appId: pageDictionary.appid,
		      path: pageDictionary.path
		    })
		  }
		} else if ('0' == pageDictionary.pageSource) {
		  if ('0' == pageDictionary.jumpMode) {
		    uni.navigateTo({
		      url: pageDictionary.path
		    })
		  } else if ('1' == pageDictionary.jumpMode) {
		    uni.redirectTo({
		      url: pageDictionary.path
		    })
		  } else if ('2' == pageDictionary.jumpMode) {
		    uni.switchTab({
		      url: pageDictionary.path
		    })
		  }
		}
		// #endif
	}
}


function getCookie(name) {
  // #ifdef H5 || MP-UNIONPAY
  var strCookie = document.cookie; //获取cookie字符串
  // #endif
  // #ifdef MP-WEIXIN
  var strCookie = ''; //获取cookie字符串
  // #endif

  var arrCookie = strCookie.split("; "); //分割
  //遍历匹配
  for (var i = 0; i < arrCookie.length; i++) {
    var arr = arrCookie[i].split("=");
    if (arr[0] == name) {
      return arr[1];
    }
  }
  return "";
}
// 将十六进制的颜色值转成rgb、rgba格式
function hexToRgba(hex, opacity) {
  return 'rgba(' + parseInt('0x' + hex.slice(1, 3)) + ',' + parseInt('0x' + hex.slice(3, 5)) + ','
          + parseInt('0x' + hex.slice(5, 7)) + ',' + opacity + ')';
}

module.exports = {
  formatTime: formatTime,
  formatTime2: formatTime2,
  formatDate: formatDate,
  formatNumber: formatNumber,
  isEmpty: isEmpty,
  base64Encode: base64Encode,
  base64Decode: base64Decode,
  verifyPhone: verifyPhone,
  message: message,
  confirm: confirm,
  loadingShow: loadingShow,
  tips: tips,
  idCardValidate: idCardValidate,
	valueTrim: valueTrim,
  checkBankCard: checkBankCard,
  isMoney: isMoney,
  switchTabLoc: switchTabLoc,
  verifyEmail: verifyEmail,
  showLoading: showLoading,
  hideLoading: hideLoading,
  formatCouponDate: formatCouponDate,
  formatDotDate: formatDotDate,
  dateStrToTimestamp: dateStrToTimestamp,
  totalMoney: totalMoney,
  getCurrentPage: getCurrentPage,
  getCurrentPageUrlWithArgs: getCurrentPageUrlWithArgs,
  getDistance: getDistance,
  openLocation: openLocation,
  isMobile: isMobile,
  decodeUrl: decodeUrl,
  toBannerUrl: toBannerUrl,
  throttle: throttle,
  debounce: debounce,
  formatCity: formatCity,
  attachedUrl: attachedUrl,
  getCookie: getCookie,
  hexToRgba,
  throttle1,
  debounce1
}
